package com.wy.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.wy.action.LoginAction;
import com.wy.entity.User;
import com.wy.util.Constant;
import com.wy.util.security.CookieUtil;
import com.wy.util.security.PurviewJudgementArithmetic;

/**
 * 登录判断、权限验证拦截器
 * @author WY
 *
 */
public class CheckLoginInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String USER_SESSION_KEY = Constant.USER_SESSION_KEY;

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {

		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, Object> session = ActionContext.getContext().getSession();
		
		//对LoginAction不做拦截:home除外
		Object action = actionInvocation.getAction();
		String actionName = actionInvocation.getInvocationContext().getName();
		if(action instanceof LoginAction && !actionName.equals("home")){
			return actionInvocation.invoke();
		}
		//验证session/cookie
		User sessionUser = null;
		User cookieUser = null;
		
		Object obj = session.get(USER_SESSION_KEY);
		if(obj != null){
			//session存在
			sessionUser = (User)obj;
			
		}else if((cookieUser = CookieUtil.validataUser(request)) != null){
			//用户信息cookie存在，保存session，继续操作
			session.put(USER_SESSION_KEY, cookieUser);
			sessionUser = cookieUser;
//			return actionInvocation.invoke();
			
		}else{
			//session、cooike不存在，返回登录页面
			return Action.LOGIN;
		}
		
		//权限验证
		if(PurviewJudgementArithmetic.doAuthorityValidate(sessionUser)){
			//验证通过
			return actionInvocation.invoke();
		}else{
			//验证不通过
			return Constant.AUTHORITY_NOT_INSUFFICIENT;
		}
		
	}

}
